//
//  JLCFBaseWebViewController.m
//  QTZ
//
//  Created by ski on 2017/8/2.
//  Copyright © 2017年 ski. All rights reserved.
//

#import "JLCFBaseWebViewController.h"
#import "JLCFRegisterService.h"
#import "JLCFWebviewProgressLine.h"
#import <UShareUI/UShareUI.h>
#import "rmMqyfJLCFLoginAndRegisterControllerFbzYtj.h"


@interface JLCFBaseWebViewController ()
{
    NSString *_tokenUrl;
    BOOL _backToHome;
}

@property (nonatomic, strong) UIButton* closeButton;//关闭按钮

@property (nonatomic, assign) BOOL hasClose;


@property (nonatomic,strong) JLCFWebviewProgressLine  *progressLine;


@end

@implementation JLCFBaseWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addNavigationBar];
    
    [self addWebView];
    [self addProgressLine];
    _tokenUrl = self.url;
    DBG(@"tokenUrl : %@", _tokenUrl);
    if (self.fuyouinfo) {
        [self loadPostRequest];
    }else{
        [self loadRequest];
    }
    
    [self JSToOc];
    
    if ([JLCFRegisterService shareService].shareId) {
        
        NSDictionary *dic = @{@"id" : [JLCFRegisterService shareService].shareId};
        
        [self.bridge callHandler:@"functionInJs" data:[NSString jsonStringWithDict:dic] responseCallback:^(id responseData) {
            DBG(@"responseData :%@", responseData);
        }];
    }
    [self.bridge registerHandler:@"submitFromWeb" handler:^(id data, WVJBResponseCallback responseCallback) {
        DBG(@"id : %@", data);
        NSDictionary *dic = (NSDictionary *)data;
        self.shareTitle = [dic safeObjectForKey:@"title"];
        self.shareDesc = [dic safeObjectForKey:@"label"];;
        self.shareUrl = [dic safeObjectForKey:@"url"];
        self.shareIcon = [UIImage imageNamed:@"icon_share"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([JLCFRegisterService shareService].hasToken) {
                [self handleShare:nil];
            } else {
                rmMqyfJLCFLoginAndRegisterControllerFbzYtj *vc = [rmMqyfJLCFLoginAndRegisterControllerFbzYtj new];
                [[[JinLiCaiFuApplicationEntrace shareEntrance] currentNavController] pushViewController:vc animated:YES];
            }
        });
    }];
}

- (void)handleShare:(UIButton *)btn
{
    //显示分享面板
    __weak __typeof(self)weakSelf = self;
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [weakSelf shareWebPageToPlatformType:platformType];
    }];
}

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:_shareTitle descr:_shareDesc thumImage:_shareImage ? _shareImage : _shareIcon];
    //设置网页地址
    shareObject.webpageUrl = self.shareUrl ? self.shareUrl : self.url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self hideNotice];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addProgressLine
{
    self.progressLine = [[JLCFWebviewProgressLine alloc] initWithFrame:CGRectMake(0, NAVBAR_HEIGHT, FULL_WIDTH, 3)];
    self.progressLine.lineColor = Theme_Color;
    [self.view addSubview:self.progressLine];
}

#pragma mark - UI
- (void)addWebView{
    
    CGRect rect = CGRectMake(0, NAVBAR_HEIGHT, FULL_WIDTH, FULL_HEIGHT - NAVBAR_HEIGHT);
    
    self.webView = [[UIWebView alloc] initWithFrame:rect];
    self.webView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.webView];
    self.webView.scalesPageToFit = YES;
    self.webView.delegate = self;
    
    //防止视频音频后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategorySoloAmbient error:nil];
    
//    if (_bridge) { return; }
//    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    [_bridge setWebViewDelegate:self];

}

- (void)addNavigationBar
{
    [super addNavigationBar];
//    self.navigationBar.titleLabel.centerY = self.navigationBar.leftBarButton.height/2;
    
//    if (!self.isShareHidden) {
//        self.shareButton = [UIButton new];
////        [self.shareButton setImage:[UIImage imageNamed:@"icon_share"] forState:UIControlStateNormal];
//    [self.shareButton setTitle:@"分享" forState:0];
//        [self.shareButton sizeToFit];
//        self.shareButton.right = FULL_WIDTH;
//        self.shareButton.centerY = NAVBAR_CENTER_Y;
//        [self.shareButton addTarget:self action:@selector(handleShare:) forControlEvents:UIControlEventTouchUpInside];
//        [self.navigationBar addSubview:self.shareButton];
////    }
}

- (void)setTitle:(NSString *)title
{
    self.navigationBar.titleLabel.text = title;
}

- (void)clickback
{
    if ([_webView canGoBack] && !self.forceBack) {
        [_webView goBack];
        if (!self.hasClose && [_webView canGoBack] && [self canGoBack]) {
            [self addCloseButton];
        }
        [self adjustTitle];
    }
    else {
        self.hasClose = NO;
        [self close];
    }
}

-(void)adjustTitle{
    if(self.hasClose){
        self.navigationBar.titleLabel.width = FULL_WIDTH - (self.closeButton.left + 40)*2;
        self.navigationBar.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.navigationBar.titleView.width = FULL_WIDTH - (self.closeButton.left + 40)*2;
        self.navigationBar.titleView.left = self.closeButton.left + 40;
    }
}

- (void)addCloseButton {
    
    self.closeButton = [[UIButton alloc]init ];
    [self.closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    [self.closeButton setTitleColor:QTZ_Gray118 forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = FONT(14);
    [self.closeButton sizeToFit];
    self.closeButton.centerY = self.navigationBar.leftBarButton.height/2;
    [self.closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    self.closeButton.left = self.navigationBar.leftBarButton.right - 10;
    [self.navigationBar.containerView addSubview:self.closeButton];
    
    self.hasClose = YES;
}

- (void)close {
    if (!_backToHome) {
        [super clickback];
    } else {
//        [[JLCFNavigationService sharedService] openUrl:@"qtz://home"];
        [[JinLiCaiFuApplicationEntrace shareEntrance].tabBarViewController setSelectedIndex:0];
        [[JinLiCaiFuApplicationEntrace shareEntrance].currentNavController popToRootViewControllerAnimated:YES];
    }
}

- (BOOL)canGoBack {
    UINavigationController *navigationController = [JinLiCaiFuApplicationEntrace shareEntrance].currentNavController;
    return navigationController.viewControllers.count > 1 && self == navigationController.viewControllers.lastObject;
}


//
- (void)loadRequest
{
    NSURL * url   = [NSURL URLWithString:[NSString stringWithFormat:@"%@", _tokenUrl]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.f];
    [self.webView loadRequest:request];
    
//    [self showLoadingViewInView:self.view];
}
- (void)loadPostRequest
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", _tokenUrl]];
    NSString *body = [NSString stringWithFormat: @"ENCTP=%@&MCHNTCD=%@&VERSION=%@&FM=%@",self.fuyouinfo.ENCTP,self.fuyouinfo.MCHNTCD,self.fuyouinfo.VERSION,self.fuyouinfo.FM];
    NSLog(@"url:%@ ",url);
    NSLog(@"body:%@",   body);
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
    [request setHTTPMethod: @"POST"];
    [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
    [self.webView loadRequest: request];
    
    
    //    [self showLoadingViewInView:self.view];
}

- (void)JSToOc
{
    
    
}

#pragma mark --------delegate--------
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    NSLog(@"webViewDidStartLoad+++%@",webView);
    [self.progressLine startLoadingAnimation];
    [self setTitle:@"加载中..."];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.progressLine endLoadingAnimation];
    NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self setTitle:title];
    
    if (!self.shareTitle) {
        self.shareTitle = title;
    }
    [self hideNotice];
    
    self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self.progressLine endLoadingAnimation];
    NSString *title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self setTitle:title];
    
    if (!self.shareTitle) {
        self.shareTitle = title;
    }
    [self hideNotice];
}



- (void)nativeback {
    [[[JinLiCaiFuApplicationEntrace shareEntrance]currentNavController]popToRootViewControllerAnimated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"1111111111111111111111111+%@",);
    if([request.mainDocumentURL.relativePath containsString:@"pay_"]){
        [self.bridge registerHandler:@"submitFromWeb1" handler:^(id data, WVJBResponseCallback responseCallback) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:MINE_REFRESH object:nil];
                [self nativeback];
                
            });
        }];
    }
    
    return YES;
}


@end
